package com.Policing.menu;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;


import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.Policing.Fragment.Abnormal;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class AbnormalActivity extends AppCompatActivity {

    private String getVersionUrl = "http://" + Ip_Set.IP + "/api/getVersionPDA";
    private String getAPK = "http://" + Ip_Set.IP + "/api/getAPKPDA";
    private FragmentManager fragmentManager;
    private Fragment abnormal, fragment2;
    private ImageView fh;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment);
        fragmentManager = getSupportFragmentManager();
        abnormal = new Abnormal();
        fragmentManager.beginTransaction().add(R.id.fragment, abnormal).commit();
        //updateVersion();
    }

    /**
     * 巡检任务
     *
     * @param view
     */
    public void policing(View view) {
        startActivity(new Intent(this, AbnormalActivity.class));
    }

    /**
     * 异常处理
     *
     * @param view
     */
    public void abnormal(View view) {

    }

    /**
     * 检查更新版本
     */
    private void updateVersion() {
        // 获取当前版本号信息
        PackageInfo packInfo = null;
        try {
            packInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        assert packInfo != null;
        final int versionCode = packInfo.versionCode;
        //获取服务器里apk版本号
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody body = new FormBody.Builder()/*.add("source",Since_case.set().getSource())*/.build();
        Request request = new Request.Builder().url(getVersionUrl).post(body).build();
        Log.e("测试数据", getVersionUrl);
        try {
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    runOnUiThread(() -> Toast.makeText(AbnormalActivity.this, "请检查网络", Toast.LENGTH_SHORT).show());

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        assert response.body() != null;
                        InputStream inputStream = response.body().byteStream();
                        //使用IO流读取数据
                        String line = null;
                        StringBuffer sb = new StringBuffer();
                        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                        while ((line = in.readLine()) != null) {
                            sb.append(line);
                        }
                        inputStream.close();
                        in.close();
                        String versionInfo = sb.toString();
                        final int updateVersion = Integer.parseInt(versionInfo.substring(versionInfo.indexOf(":") + 1));
                        Log.i("测试1", "version: " + versionCode + "--updateVersion:" + updateVersion);
                        //是否弹出有高版本时可以更新的提示框
                        if (versionCode < updateVersion) {
                            runOnUiThread(() -> {
                                final AlertDialog builder = new AlertDialog.Builder(AbnormalActivity.this)
                                        .setTitle("更新提示")
                                        .setMessage("有新版本是否更新！")
                                        .setNegativeButton("否", (dialog, which) -> dialog.dismiss())
                                        .setPositiveButton("是", (dialog, which) -> {
                                            downloadAPK();
                                            dialog.dismiss();
                                        }).create();
                                builder.setCanceledOnTouchOutside(false);
                                builder.show();
                            });
                        }
                    } else {
                        Log.i("测试", "请求错误 ");
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            Log.i("测试", "请求错误 ");
        }

    }

    /**
     * 下载最新版apk
     */
    private void downloadAPK() {
        //弹出进度提示框
        showDialog(AbnormalActivity.this);
        OkHttpClient okHttpClient = new OkHttpClient();
        final FormBody body = new FormBody.Builder().build();
        final Request request = new Request.Builder().url(getAPK).post(body).addHeader("Accept-Encoding", "identity").build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(AbnormalActivity.this, "请检查网络！", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    assert response.body() != null;
                    final InputStream in = response.body().byteStream();
                    //保存SD卡
                    final File path = new File(Environment.getExternalStorageDirectory(), "Xt_slab_apk_pda");
                    Log.e("测试", String.valueOf(path));
                    if (!path.exists()) {//判断路径文件夹是否存在
                        path.mkdirs();//创建文件夹
                    }
                    final File file = new File(path, "app.apk");
                    if (file.exists()) {//判断路径文件是否存在
                        file.delete();//删除文件
                    }
                    if (!file.exists()) {
                        file.createNewFile();//创建文件
                        FileOutputStream output = null;
                        try {
                            output = new FileOutputStream(file);
                            int len = 0;
                            byte[] buffer = new byte[1024];
                            while ((len = in.read(buffer)) != -1) {
                                output.write(buffer, 0, len);
                                Log.i("测试", "len: " + len);
                            }
                            output.flush();
                        } catch (IOException e) {
                            Log.i("测试", "IOException: ");
                        }
                        assert output != null;
                        output.close();
                    }

                    runOnUiThread(() -> {
                        progressDialog.cancel();
                        // 安装apk
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        Uri data;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断版本大于等于7.0
                            // 通过FileProvider创建一个content类型的Uri
                            data = FileProvider.getUriForFile(AbnormalActivity.this, "com.Assetspolling.provider", file);
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 给目标应用一个临时授权
                        } else {
                            data = Uri.fromFile(file);
                        }
                        intent.setDataAndType(data, "application/vnd.android.package-archive");
                        startActivity(intent);
                    });

                } else {
                    Log.i("测试", "服务器异常！");
                }
            }
        });
    }

    private ProgressDialog progressDialog;

    private void showDialog(final Context context) {
        runOnUiThread(() -> {
            progressDialog = new ProgressDialog(context);
            progressDialog.setTitle("正在下载中");
            progressDialog.setMessage("Loading...");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        });
    }


}
